const { createApp } = Vue;

createApp({
    data() {
        return {
            formData: {
                username: '',
                email: '',
                password: '',
                confirmPassword: '',
                agreement: false
            },
            errors: {
                username: '',
                email: '',
                password: '',
                confirmPassword: '',
                agreement: ''
            },
            isSubmitting: false
        };
    },
    methods: {
        async handleSubmit() {
            // 清除所有错误
            this.clearAllErrors();

            // 验证表单
            if (!this.validateForm()) {
                return;
            }

            this.isSubmitting = true;

            try {
                // 发送注册请求
                const response = await this.registerUser();

                if (response.success) {
                    this.errors.agreement = response.message;
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    // 注册成功，跳转到登录页面
                    window.location.href = '/static/html/login.html';
                } else {
                    // 显示服务器返回的错误信息
                    this.showServerError(response.message);
                }
            } catch (error) {
                console.error('注册错误:', error);
                this.errors.general = '注册过程中发生错误，请稍后重试';
            } finally {
                this.isSubmitting = false;
            }
        },

        validateForm() {
            let isValid = true;

            // 检查用户名
            if (this.formData.username.length < 4 || this.formData.username.length > 20) {
                this.errors.username = '用户名长度必须在4-20个字符之间';
                isValid = false;
            }

            // 检查邮箱格式
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(this.formData.email)) {
                this.errors.email = '请输入有效的电子邮箱地址';
                isValid = false;
            }

            // 检查密码长度
            if (this.formData.password.length < 6) {
                this.errors.password = '密码长度不能少于6个字符';
                isValid = false;
            }

            // 检查密码匹配
            if (this.formData.password !== this.formData.confirmPassword) {
                this.errors.confirmPassword = '两次输入的密码不一致';
                isValid = false;
            }

            // 检查用户协议
            if (!this.formData.agreement) {
                this.errors.agreement = '请阅读并同意用户协议';
                isValid = false;
            }

            return isValid;
        },

        clearError(field) {
            this.errors[field] = '';
        },

        clearAllErrors() {
            Object.keys(this.errors).forEach(key => {
                this.errors[key] = '';
            });
        },

        showServerError(message) {
            // 这里可以根据服务器返回的错误信息，判断是哪个字段出错
            // 简单处理，显示在第一个错误位置
            console.log(message);
            
            this.errors.agreement = message || '注册失败，请检查输入信息';
        },

        async registerUser() {
            // 这里应该是实际的API调用
            // 示例中使用模拟API响应
            const mockApiResponse = {
                success: true,
                message: '注册成功'
            };
            
            try {
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: this.formData.username,
                        email: this.formData.email,
                        password: this.formData.password
                    })
                });
                
                console.log(response);
                

                if(200 === response.status)
                {
                    mockApiResponse.success = true;
                    mockApiResponse.message = "注册成功";
                }
                else
                {
                    mockApiResponse.success = false;
                    mockApiResponse.message = "注册失败";
                }
            } catch (error) {
                throw error;
            }
            
            return mockApiResponse;
        }
    }
}).mount('#app');
